package com.heer.gymnasium.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.heer.gymnasium.api.Http;
import com.heer.gymnasium.api.callback.RequestCallback;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.user.beans.WxUserBean;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhihuiyun.library.utils.L;

import java.util.HashMap;
import java.util.Map;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, IConstants.APPID_WX, false);

        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {

        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                break;
            case ConstantsAPI.COMMAND_LAUNCH_BY_WX:
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        String code = "";
        Log.e("Wx_onResp", "code = " + resp.errCode + "  --  " + resp.errStr);
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            //Toast.makeText(this, "code = " + (code = ((SendAuth.Resp) resp).code), Toast.LENGTH_SHORT).show();
            Log.e("WxAuth_onResp", "code = " + (code = ((SendAuth.Resp) resp).code));
        }

        String result = "";

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    result = "分享成功";
                } else {
                    if (TextUtils.equals("wechat_sdk_gym_login", ((SendAuth.Resp) resp).state)) {
                        getWxId(code);
                    }
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "分享取消";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "认证失败";
                break;
            default:
                result = "未知状态";
                break;
        }
        L.e("Wx_onResp ", "通知回调 " + result);
        if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        }
        finish();
    }

    private void getWxId(String code) {
        L.e("登录 code " + code);
        Map<String, String> params = new HashMap<>();
        String wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
                + "?appid=wxe1d69964f9c45a9d"
                + "&secret=8ba9312d2220de2f65b935935b732563"
                + "&grant_type=authorization_code"
                + "&code=" + code;
        Http.get(wx_url
                , params, new RequestCallback<String>() {
                    @Override
                    public void onSuccess(String jsonStr) {
                        super.onSuccess(jsonStr);
                        Log.e("wx_auth", jsonStr.toString());
                        WxUserBean user = (new Gson()).fromJson(jsonStr, WxUserBean.class);
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = user.getUnionid();
                        L.e("登录 getUnionid " + user.getUnionid());
                        LoginActivity.mHandler.sendMessage(msg);

                    }

                    @Override
                    public void onFailure(int code, String error) {
                        super.onFailure(code, error);
                    }
                });
    }

}